package qinggui.mlz.module.index;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qinggui.mlz.module.article.service.ArticleService;
import qinggui.mlz.module.category.service.CategoryService;
import qinggui.mlz.module.star.service.StarService;
import qinggui.mlz.module.tag.service.TagService;

import java.util.Map;
import java.util.concurrent.*;

@Service
@Slf4j
public class IndexService {
    @Autowired
    private StarService starService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TagService tagService;
    @Autowired
    private ArticleService articleService;

    /**
     * 获取首页数据
     *
     * @return List
     */
    public Map<String, Object> getIndexData() throws InterruptedException {
        // 1. 多线程实现，采用一等多的CountDownLatch
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3, 8, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100),
                new ThreadFactoryBuilder().setNameFormat("index-thread-").build(),
                new ThreadPoolExecutor.CallerRunsPolicy());// 触发拒绝策略时候，由提交任务的线程自己执行
        CountDownLatch latch = new CountDownLatch(3);   // 只有 3 个异步任务
        Map<String, Object> result = new ConcurrentHashMap<>();
        // 2. 异步任务
        pool.execute(() -> {
            try {
                result.put("starList", starService.getAllList(1, 10));
            } catch (Exception e) {
                log.error("star查询异常", e);
            } finally {
                latch.countDown();
            }
        });

        pool.execute(() -> {
            try {
                result.put("categories", categoryService.getAllParentCategory(""));
            } catch (Exception e) {
                log.error("category查询异常", e);
            } finally {
                latch.countDown();
            }
        });

        pool.execute(() -> {
            try {
                result.put("tags", tagService.getAllList());
            } catch (Exception e) {
                log.error("tag查询异常", e);
            } finally {
                latch.countDown();
            }
        });

        // 3. 主线程自己干
        result.put("articles", articleService.getArticleList(1, 10, ""));

        // 4. 等待 + 必关线程池
        latch.await();
        pool.shutdown();   // 必须关闭，否则泄漏
        return result;
    }
}
